import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { ArrowLeft, Trophy, Eye, Sword, TrendingUp, Target } from 'lucide-react'
import { VisionMasterRanking, KillingMachineRanking, LeagueMatch, LeagueDetail } from '@/types/dota'
import openDotaAPI from '@/services/api'

interface LeagueRankingsProps {
  leagueId: number
  leagueName: string
  onBack: () => void
  cachedMatches?: LeagueMatch[] // 可选的缓存比赛数据
  cachedLeagueDetail?: LeagueDetail // 新增：可选的缓存联赛详情
}

export default function LeagueRankings({ leagueId, leagueName, onBack, cachedMatches, cachedLeagueDetail }: LeagueRankingsProps) {
  const [activeTab, setActiveTab] = useState('vision')
  const [visionData, setVisionData] = useState<VisionMasterRanking | null>(null)
  const [killingData, setKillingData] = useState<KillingMachineRanking | null>(null)
  const [loading, setLoading] = useState(false)
  const [progress, setProgress] = useState(0)
  const [progressMessage, setProgressMessage] = useState('')

  // 加载视野大师排行榜
  const loadVisionMasterRanking = async () => {
    if (visionData) return // 已加载过
    
    setLoading(true)
    setProgress(0)
    setProgressMessage('正在加载视野大师排行榜...')
    
    try {
      const data = await openDotaAPI.getVisionMasterRanking(
        leagueId,
        (current, _, message) => {
          setProgress(current)
          setProgressMessage(message)
        },
        cachedMatches, // 传递缓存的比赛数据
        cachedLeagueDetail // 传递缓存的联赛详情
      )
      setVisionData(data)
    } catch (error) {
      console.error('加载视野大师排行榜失败:', error)
    } finally {
      setLoading(false)
      setProgress(0)
      setProgressMessage('')
    }
  }

  // 加载杀戮机器排行榜
  const loadKillingMachineRanking = async () => {
    if (killingData) return // 已加载过
    
    setLoading(true)
    setProgress(0)
    setProgressMessage('正在加载杀戮机器排行榜...')
    
    try {
      const data = await openDotaAPI.getKillingMachineRanking(
        leagueId,
        (current, _, message) => {
          setProgress(current)
          setProgressMessage(message)
        },
        cachedMatches, // 传递缓存的比赛数据
        cachedLeagueDetail // 传递缓存的联赛详情
      )
      setKillingData(data)
    } catch (error) {
      console.error('加载杀戮机器排行榜失败:', error)
    } finally {
      setLoading(false)
      setProgress(0)
      setProgressMessage('')
    }
  }

  // 根据当前标签页加载数据
  useEffect(() => {
    if (activeTab === 'vision') {
      loadVisionMasterRanking()
    } else if (activeTab === 'killing') {
      loadKillingMachineRanking()
    }
  }, [activeTab])

  // 渲染视野大师排行榜表格
  const renderVisionMasterTable = () => {
    if (!visionData) return null

    return (
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-16">排名</TableHead>
            <TableHead>玩家</TableHead>
            <TableHead className="text-center">比赛场次</TableHead>
            <TableHead className="text-center">平均插眼数</TableHead>
            <TableHead className="text-center">最高单场插眼</TableHead>
            <TableHead className="text-center">胜率</TableHead>
            <TableHead className="text-center">胜/负</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {visionData.players.map((player, index) => (
            <TableRow key={player.account_id}>
              <TableCell className="font-medium">
                <div className="flex items-center gap-2">
                  {index < 3 && (
                    <Trophy className={`w-4 h-4 ${
                      index === 0 ? 'text-yellow-500' : 
                      index === 1 ? 'text-gray-400' : 
                      'text-amber-600'
                    }`} />
                  )}
                  #{index + 1}
                </div>
              </TableCell>
              <TableCell>
                <div className="flex items-center gap-2">
                  {player.avatar && (
                    <img 
                      src={player.avatar} 
                      alt={player.personaname}
                      className="w-8 h-8 rounded-full"
                    />
                  )}
                  <span className="font-medium">{player.personaname}</span>
                </div>
              </TableCell>
              <TableCell className="text-center">{player.matches_played}</TableCell>
              <TableCell className="text-center">
                <Badge variant="secondary" className="bg-blue-100 text-blue-800">
                  <Eye className="w-3 h-3 mr-1" />
                  {player.avg_wards_per_match}
                </Badge>
              </TableCell>
              <TableCell className="text-center">
                <Badge variant="outline" className="border-blue-300">
                  <Target className="w-3 h-3 mr-1" />
                  {player.max_wards_single_match}
                </Badge>
              </TableCell>
              <TableCell className="text-center">
                <Badge 
                  variant={player.win_rate >= 60 ? "default" : player.win_rate >= 50 ? "secondary" : "destructive"}
                  className={
                    player.win_rate >= 60 ? "bg-green-100 text-green-800" :
                    player.win_rate >= 50 ? "bg-yellow-100 text-yellow-800" :
                    "bg-red-100 text-red-800"
                  }
                >
                  <TrendingUp className="w-3 h-3 mr-1" />
                  {player.win_rate}%
                </Badge>
              </TableCell>
              <TableCell className="text-center text-sm text-muted-foreground">
                {player.total_wins}胜 / {player.total_losses}负
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    )
  }

  // 渲染杀戮机器排行榜表格
  const renderKillingMachineTable = () => {
    if (!killingData) return null

    return (
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-16">排名</TableHead>
            <TableHead>玩家</TableHead>
            <TableHead className="text-center">比赛场次</TableHead>
            <TableHead className="text-center">平均击杀数</TableHead>
            <TableHead className="text-center">最高单场击杀</TableHead>
            <TableHead className="text-center">胜率</TableHead>
            <TableHead className="text-center">胜/负</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {killingData.players.map((player, index) => (
            <TableRow key={player.account_id}>
              <TableCell className="font-medium">
                <div className="flex items-center gap-2">
                  {index < 3 && (
                    <Trophy className={`w-4 h-4 ${
                      index === 0 ? 'text-yellow-500' : 
                      index === 1 ? 'text-gray-400' : 
                      'text-amber-600'
                    }`} />
                  )}
                  #{index + 1}
                </div>
              </TableCell>
              <TableCell>
                <div className="flex items-center gap-2">
                  {player.avatar && (
                    <img 
                      src={player.avatar} 
                      alt={player.personaname}
                      className="w-8 h-8 rounded-full"
                    />
                  )}
                  <span className="font-medium">{player.personaname}</span>
                </div>
              </TableCell>
              <TableCell className="text-center">{player.matches_played}</TableCell>
              <TableCell className="text-center">
                <Badge variant="secondary" className="bg-red-100 text-red-800">
                  <Sword className="w-3 h-3 mr-1" />
                  {player.avg_kills_per_match}
                </Badge>
              </TableCell>
              <TableCell className="text-center">
                <Badge variant="outline" className="border-red-300">
                  <Target className="w-3 h-3 mr-1" />
                  {player.max_kills_single_match}
                </Badge>
              </TableCell>
              <TableCell className="text-center">
                <Badge 
                  variant={player.win_rate >= 60 ? "default" : player.win_rate >= 50 ? "secondary" : "destructive"}
                  className={
                    player.win_rate >= 60 ? "bg-green-100 text-green-800" :
                    player.win_rate >= 50 ? "bg-yellow-100 text-yellow-800" :
                    "bg-red-100 text-red-800"
                  }
                >
                  <TrendingUp className="w-3 h-3 mr-1" />
                  {player.win_rate}%
                </Badge>
              </TableCell>
              <TableCell className="text-center text-sm text-muted-foreground">
                {player.total_wins}胜 / {player.total_losses}负
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    )
  }

  return (
    <div className="space-y-6">
      {/* 头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回联赛详情
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{leagueName} - 排行榜</h1>
            <p className="text-muted-foreground">联赛玩家表现统计排名</p>
          </div>
        </div>
      </div>

      {/* 加载进度 */}
      {loading && (
        <Card>
          <CardContent className="pt-6">
            <div className="space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span>{progressMessage}</span>
                <span>{progress}%</span>
              </div>
              <Progress value={progress} className="w-full" />
            </div>
          </CardContent>
        </Card>
      )}

      {/* 排行榜标签页 */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="vision" className="flex items-center gap-2">
            <Eye className="w-4 h-4" />
            视野大师
          </TabsTrigger>
          <TabsTrigger value="killing" className="flex items-center gap-2">
            <Sword className="w-4 h-4" />
            杀戮机器
          </TabsTrigger>
        </TabsList>

        {/* 视野大师排行榜 */}
        <TabsContent value="vision">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Eye className="w-5 h-5 text-blue-600" />
                视野大师排行榜
              </CardTitle>
              <p className="text-sm text-muted-foreground">
                根据平均每场插眼数（真眼+假眼）排名，显示最高单场插眼数和胜率
                {visionData && ` • 共 ${visionData.total_players} 名玩家`}
              </p>
            </CardHeader>
            <CardContent>
              {!loading && visionData ? (
                renderVisionMasterTable()
              ) : !loading ? (
                <div className="text-center py-8 text-muted-foreground">
                  点击标签页加载数据
                </div>
              ) : null}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 杀戮机器排行榜 */}
        <TabsContent value="killing">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Sword className="w-5 h-5 text-red-600" />
                杀戮机器排行榜
              </CardTitle>
              <p className="text-sm text-muted-foreground">
                根据平均每场击杀数排名，显示最高单场击杀数和胜率
                {killingData && ` • 共 ${killingData.total_players} 名玩家`}
              </p>
            </CardHeader>
            <CardContent>
              {!loading && killingData ? (
                renderKillingMachineTable()
              ) : !loading ? (
                <div className="text-center py-8 text-muted-foreground">
                  点击标签页加载数据
                </div>
              ) : null}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
